package com.xydtech.ecard.ecard.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xydtech.common.config.XydtechBusiPlatConfig;
import com.xydtech.common.constant.Constants;
import com.xydtech.common.enums.ApiContant;
import com.xydtech.common.exception.ApiException;
import com.xydtech.common.model.ResponseModel;
import com.xydtech.common.utils.AESEncryptionUtils;
import com.xydtech.common.utils.PdfUtil;
import com.xydtech.common.utils.StringUtils;
import com.xydtech.common.utils.uuid.IdUtils;
import com.xydtech.data.DataPlatHttpUtils;
import com.xydtech.ecard.busi.domain.EcardApiEcardBusiReservation;
import com.xydtech.ecard.busi.mapper.EcardApiEcardBusiReservationMapper;
import com.xydtech.ecard.ecard.service.EcardApiWeiZongService;
import com.xydtech.system.service.ISysConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.List;
import java.util.Map;

/**
 * 微众接口服务
 *
 * @author yjs
 * @date 2022/7/26 14:32
 */

@Service
public class EcardApiWeiZongServiceImpl implements EcardApiWeiZongService {
    private static final Logger log = LoggerFactory.getLogger(EcardApiWeiZongServiceImpl.class);
    @Autowired
    private ISysConfigService configService;
    @Autowired
    DataPlatHttpUtils dataPlatHttpUtils;
    @Autowired
    private EcardApiEcardBusiReservationMapper ecardApiEcardBusiReservationMapper;

    /**
     * 商易通企业授权认证接口
     *
     * @author yjs
     * @date 2022/7/26 14:31
     */
    @Override
    public ResponseModel goAuthorize(Map<String, Object> paramMap) throws Exception {
        //企业授权认证地址
        String interfaceNumOcr = configService.selectConfigByKey(ApiContant.DATAPLAT_INTERFACENUMORGCERTAUTH_KEY, Long.valueOf(paramMap.get("deptId").toString()));
        ResponseModel responseModel = dataPlatHttpUtils.dataPlatRequest(interfaceNumOcr, paramMap.get("appId").toString(), ApiContant.APPLETTYPE_ECARD, null, paramMap);
        return responseModel;
    }

    /**
     * 查询授权结果
     *
     * @author yjs
     * @date 2022/7/28 9:09
     */
    @Override
    public ResponseModel getAuthorizeInfo(Map<String, Object> paramMap, String salt) throws Exception {
        List<EcardApiEcardBusiReservation> ecardBusiReservations = ecardApiEcardBusiReservationMapper.getReservationDetail(paramMap.get("resId").toString());
        if (ecardBusiReservations.size() > 0) {
            for (EcardApiEcardBusiReservation busiReservation : ecardBusiReservations) {
                try {
                    //数据解密（手机号、身份证号）
                    if (!StringUtils.objIsNullOrEmpty(busiReservation.getTelNo())) {
                        busiReservation.setTelNo(AESEncryptionUtils.decrypt(busiReservation.getTelNo(), salt));
                    }
                    if (!StringUtils.objIsNullOrEmpty(busiReservation.getCardNum())) {
                        busiReservation.setCardNum(AESEncryptionUtils.decrypt(busiReservation.getCardNum(), salt));
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
        //纳税人识别号
        paramMap.put("taxNumber", ecardBusiReservations.get(0).getTaxNumber());
        //证件号码
        paramMap.put("idCardNumber", ecardBusiReservations.get(0).getTaxNumber());
        String interfaceNum = configService.selectConfigByKey(ApiContant.DATAPLAT_INTERFACENUMQUERYORGCERTAUTH_KEY, Long.valueOf(paramMap.get("deptId").toString()));
        ResponseModel responseModel = dataPlatHttpUtils.dataPlatRequest(interfaceNum, paramMap.get("appId").toString(), ApiContant.APPLETTYPE_ECARD, null, paramMap);
        return responseModel;
    }

    /**
     * 查询企业税务报告
     *
     * @author yjs
     * @date 2022/7/28 9:10
     */
    @Override
    public JSONObject getReportInfo(Map<String, Object> paramMap, String salt) throws Exception {
        JSONObject jsonObject = new JSONObject();
        List<EcardApiEcardBusiReservation> ecardBusiReservations = ecardApiEcardBusiReservationMapper.getReservationDetail(paramMap.get("resId").toString());
        if (ecardBusiReservations.size() > 0) {
            for (EcardApiEcardBusiReservation busiReservation : ecardBusiReservations) {
                try {
                    //数据解密（手机号、身份证号）
                    if (!StringUtils.objIsNullOrEmpty(busiReservation.getTelNo())) {
                        busiReservation.setTelNo(AESEncryptionUtils.decrypt(busiReservation.getTelNo(), salt));
                    }
                    if (!StringUtils.objIsNullOrEmpty(busiReservation.getCardNum())) {
                        busiReservation.setCardNum(AESEncryptionUtils.decrypt(busiReservation.getCardNum(), salt));
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
        //证件号码
        paramMap.put("idCardNumber", ecardBusiReservations.get(0).getTaxNumber());
        //纳税人识别号
        paramMap.put("taxNumber", ecardBusiReservations.get(0).getTaxNumber());
        paramMap.put("name", ecardBusiReservations.get(0).getCname());
        //接口编号，报告类型：01企业交易分析报告，02企业财税分析报告
        String interfaceNum = "";
        if ("01".equals(paramMap.get("reportType").toString())) {
            interfaceNum = configService.selectConfigByKey(ApiContant.DATAPLAT_INTERFACENUMQUERYORGTRANSREPROT_KEY, Long.valueOf(paramMap.get("deptId").toString()));
        } else {
            interfaceNum = configService.selectConfigByKey(ApiContant.DATAPLAT_INTERFACENUMQUERYORGTAXREPROT_KEY, Long.valueOf(paramMap.get("deptId").toString()));
        }


        ResponseModel responseModel = dataPlatHttpUtils.dataPlatRequest(interfaceNum, paramMap.get("appId").toString(), ApiContant.APPLETTYPE_ECARD, null, paramMap);
        if (responseModel.getCode() != 0) {
            throw new ApiException("查询失败:" + responseModel.getMsg());
        }
        /**
         * 将拿到的报告PDF转换成图片文件，并将地址存储在数据库中（为兼容前端IOS和Android无法展示PDF的问题，修改成图片）
         */
        JSONObject reportInfoObj = JSONObject.parseObject(JSON.toJSONString(responseModel.getData()));
        String reportUrl = reportInfoObj.getString("taxReportUrl");

        //首先是获取到PDF文件
        String fileName = IdUtils.randomUUID() + ".png";
        //存储到硬盘中的物理地址
        String filePath = XydtechBusiPlatConfig.getProfile() + "/" + paramMap.get("deptId").toString() + "/ecard/vz/";
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        //存储到数据库中的地址
        String viewPath = Constants.RESOURCE_PREFIX + "/" + paramMap.get("deptId").toString() + "/ecard/vz/" + fileName;

        //pdf文件写入磁盘
        String pdfFile = filePath + IdUtils.randomUUID() + ".pdf";
        StringUtils.base64StringToPdf(reportInfoObj.get("taxReportData").toString(), pdfFile);
        //pdf去掉首尾页
        String newPdfFile = filePath + IdUtils.randomUUID() + ".pdf";
        PdfUtil.splitPDFFile(pdfFile, newPdfFile);
        // pdf转图片加水印
        String imgPath = filePath + fileName;
        PdfUtil.pdfToImgAddWaterMask(newPdfFile, imgPath, paramMap.get("name").toString(), 2);
        //PDF文件返回路径
        String pdfUrl = Constants.RESOURCE_PREFIX + newPdfFile.substring(newPdfFile.indexOf(paramMap.get("deptId").toString()) - 1, newPdfFile.length());
        jsonObject.put("newPdfFile", pdfUrl);
        jsonObject.put("viewPath", viewPath);
        return jsonObject;
    }


}
